/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
**/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.formbeans.LoginForm;

public class LoginAction extends Action {

	private FormBeanFactory<LoginForm> formFactory = FormBeanFactory
			.getInstance(LoginForm.class);

	public LoginAction() {
	}

	public String getName() {
		return "login.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);

		try {

			User user = new User();
			LoginForm form = formFactory.create(request);
			request.setAttribute("form", form);

			if (!form.isPresent()) {
				return "welcome.jsp";
			}

			errors.addAll(form.getValidationErrors());
			Session dbSession = DBHelper.getSessionFactory().openSession();
			if (errors.size() == 0) {
				List list = dbSession.createCriteria(User.class).add(Restrictions.eq("username", form.getUsername())).list();
				if (list.size() == 0) {
					errors.add("UserName doesn't exists");
				}
				else {
					User userBean = (User) list.get(0);
					if(!userBean.getPassword().equals(form.getPassword())) {
						errors.add("Invalid Password");
					}
					else
					{
						request.setAttribute("user", userBean);
						request.getSession().setAttribute("user", userBean);
					}
				}
			}

			if (errors.size() > 0) {
				return "welcome.jsp";
			}

			return "redirectToHome.jsp";
			
		} catch (FormBeanException e) {
			errors.add(e.toString());
			return "error.jsp";
		}
	}
}
